<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('video.video_title')">
        <el-input
          v-model="form.video_title"
          clearable
          :placeholder="t('video.video_title')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('video.operator')">
        <el-select
          v-model="form.creator"
          :filterable="true"
          :placeholder="t('video.operator')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in operatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('video.time')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          format="YYYY/MM/DD"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleJump('add')">
        {{ t('system.marketChannel.add') }}
      </el-button>
      <el-button @click="handleBatch('delete')" type="danger">
        {{ t('system.marketChannel.delete') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('expandCustomer.serialNumber')" prop="id" min-width="70" />
      <el-table-column
        :label="t('video.video_title')"
        min-width="200"
        :show-overflow-tooltip="true"
        prop="video_title"
      />
      <el-table-column
        :label="t('video.coverimage_id')"
        prop="coverimage_id"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          <el-image
            v-if="row.coverimage_url"
            style="width: 100px; height: 100px"
            :src="row.coverimage_url"
            :preview-teleported="true"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[row.coverimage_url]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column :label="t('video.video_id')" width="200">
        <template #default="{ row }">
          <el-link type="primary" :href="row.video_url" target="_blank">
            {{ t('video.jump') }}
          </el-link>
          <el-button type="primary" link @click="handleCopy(row.video_url)">
            {{ t('video.copy') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column :label="t('video.showstate')" min-width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.showstate"
            inlinePrompt
            active-text="对外显示"
            inactive-text="不对外显示"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeStatus('single', row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('video.pm_names')"
        min-width="100"
        :show-overflow-tooltip="true"
        prop="pm_names"
      />
      <el-table-column
        :label="t('video.blogger_name')"
        min-width="100"
        prop="blogger_name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('video.publish_time')"
        min-width="100"
        prop="publish_time"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('video.category')"
        min-width="100"
        prop="category"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(categoryList, row.category) }}
        </template>
      </el-table-column>

      <el-table-column
        :label="t('supply.create_time')"
        min-width="100"
        prop="create_time"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.creator')"
        min-width="100"
        prop="creator_name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.update_time')"
        min-width="180"
        prop="update_time"
        :show-overflow-tooltip="true"
      />

      <el-table-column fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button @click="handleJump('edit', row)" size="small">
            {{ t('system.marketChannel.edit') }}
          </el-button>
          <el-button type="success" @click="handleJump('detail', row)" size="small">
            {{ t('video.detail') }}
          </el-button>
          <el-button type="danger" @click="handleDelete('single', row)" size="small">
            {{ t('video.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { changeStatusApi, delDataApi, getEnumApi, getListApi } from '@/api/market/VideoManage'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { useClipboard } from '@vueuse/core'

const { copy } = useClipboard()
const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const categoryList = ref<any[]>([])
const multipleSelection = ref<any[]>([])

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  video_title: '',
  start_date: '',
  end_date: '',
  pageIndex: 1,
  pageSize: 20
})

const modelList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])

const statusList = ref<Array<Record<string, any>>>([
  { label: '对外显示', value: 1 },
  { label: '不对外显示', value: 0 }
])

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_date = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_date = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_date = null
    form.value.end_date = null
  }
}

const handleCopy = (text: string) => {
  ;(copy(text) as any) && ElMessage.success('复制成功')
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

//点击跳转
const handleJump = (type: string, row?: Record<string, any>) => {
  push({
    path: `/market/videoManage/${type}`,
    query: { [(row && 'id') as string]: row?.id }
  })
}

//批量操作
const handleBatch = async (type: string) => {
  const functionMap = {
    open: () => handleChangeStatus('open', { status: 1 }),
    close: () => handleChangeStatus('close', { status: 0 }),
    delete: () => handleDelete('batch', {})
  }
  if (functionMap[type]) functionMap[type]()
}

//点击删除
const handleDelete = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delDataApi({
        ids:
          type === 'single'
            ? [row.id]
            : multipleSelection.value.map((item: Record<string, any>) => item.id)
      })
      ElMessage.success(t('purchase.logistics.deleteSuccess'))
      await initialize()
    })
    .catch(() => {})
}

const handleChangeStatus = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(
    `是否确认显示状态流转为${row.status === 1 ? '对外显示' : '不对外显示'}？`,
    t('purchase.logistics.tips'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const resp = await changeStatusApi({
          id: row.id,
          showstate: row.showstate
        })
        if (resp.code === 0) {
          ElMessage.success(t('market.industryNews.statusMsg'))
          await initialize()
        }
      } catch (e) {
        await initialize()
      }
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1
    })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  modelList.value = resp.data.model
  operatorList.value = resp.data.operator
  categoryList.value = resp.data.category
  console.log(resp)
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    video_title: '',
    start_date: '',
    end_date: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
</script>

<style lang="less" scoped></style>
